import React, { useEffect, useMemo, useState } from 'react'
import { Table, Card, Select, Tag, Alert, Button, Space, Popconfirm, message } from 'antd'
import $http from '@/services/http.service.v2';
import $helper from '@/services/helper.service';

const ItemIDSet = {
  "668": { name: "锻造专注" },
  "669": { name: "附魔专注" },
  "212306": { name: "奇思合计" },
  "38682": { name: "附魔羊皮纸" },
  "213610": { name: "晶脉粉末" },
  "224765": { name: "点火装置" },
  "223692": { 
    name: "晶脉辉煌3星",
    regents: {
      "219947": 75,
      "219950": 10,
      "219954": 1,
      "213610": 20,
    }
  },
  "222428": { 
    name: "镔爪合金3星",
    regents: {
      "222418": 2,
      "210937": 5,
      "226202": 5,
      "213610": 1,
    }
  },
  "223790": { 
    name: "诅咒急速3星",
    regents: {
      "219947": 50,
      "219950": 10,
      "219954": 1,
      "213611": 10,
    }
  },
  "219947": { name: "风暴之尘" },
  "219950": { name: "粼光碎片" },
  "219954": { name: "耀辉水晶" },
  "222418": { name: "心核合金" },
  "210937": { name: "镔爪框" },
  "226202": { name: "回音助溶剂" },
  "213611": { name: "蠕动样本" },
  "163036": { name: "宠物币" },
}


export default function AnalyzePage() {
  const [data, setData] = useState({dateList: [], dataSource: []})
  const [selectDate, setSelectDate] = useState("")
  useEffect(() => {
    $http.getCraftLog().subscribe(
      res => {
        const list = res.data.map(parseLine).filter(_ => _ !== undefined)
        const dateList = [...new Set(list.map(item => item.date))].reverse()
        setData({dataSource: list, dateList})
        setSelectDate([...dateList].shift())
      }
    )
  }, [])
  function parseLine(line) {
    const types = ["CHECK_REAGENTS", "TRADE_SKILL_ITEM_CRAFTED_RESULT"]
    if (types.every(type => !line.includes(type))){
      return undefined
    }
    
    const lineTime = line.match(/\[.*?\]/g)[0].replace("]", "").replace("[", "")
    const lineContent = line.match(/\{.*?\}/g)[0].replace("{", "").replace("}", "")
    let lineObject = {}
    new URLSearchParams(lineContent).forEach((value, key) => {
      lineObject[key] = value
    })
    return {
      ...lineObject,
      time: lineTime,
      date: lineTime.split(" ")[0],
      type: types.find(type => line.includes(type))
    }
  }
  function onDateChange(date) {
    setSelectDate(date)
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'role_name',
      render: (_, _record, index) => {
        return <a>{index + 1}</a>
      },
    },
    {
      title: '角色',
      dataIndex: 'role_name',
      // width: 200,
      render: (_, record) => <p>{_}<br/>{record.time}</p>,
    },
    {
      title: "背包材料",
      children: [
        { title: "奇剂", dataIndex: "itemID_212306", 
          render: (_) => <Tag color={_ < 2 ? "red" : ""}>奇{_}</Tag> 
        },
        { title: "羊皮", dataIndex: "itemID_38682", render: (_) => <>羊{_}</>},
        { title: "晶末", dataIndex: "itemID_213610", 
          render: (_) => <Tag color={_ < 100 ? "red" : ""}>粉{_}</Tag> 
        },
        { title: "点火", dataIndex: "itemID_224765", render: (_) => <><span className={_ >= 2 ? "" : "text-red-500"}>点{_}</span></> },
        { title: "晶煌", dataIndex: "itemID_223692", render: (_) => <>晶{_}</> },
        { title: "镔金", dataIndex: "itemID_222428", render: (_) => <>镔{_}</> },
        { title: "诅速", dataIndex: "itemID_223790", render: (_) => <>诅{_}</> },
        { title: "锻注", dataIndex: "itemID_668", render: (_) => <>dz{_}</> },
        { title: "附注", dataIndex: "itemID_669", render: (_) => <>fm{_}</> },
        { title: "铁砧", dataIndex: "itemID_87216", render: (_) => <><span className={_ >= 2 ? "" : "text-red-500"}>铁{_}</span></> },
        { title: "宠币", dataIndex: "itemID_163036", render: (_) => <>宠{_}</> },
      ]
    },
  ];
  function formatCyList(cy_list) {
    let obj = {}
    cy_list.forEach(item => {
      let key = Object.keys(item)[0].replace("resourcesReturned_", "")
      if (!obj[key]) {
        obj[key] = +Object.values(item)[0]
      } else {
        obj[key] += +Object.values(item)[0]
      }
    })
    return Object.keys(obj).map(k => {
      return `${ItemIDSet[k].name}=${obj[k]}`
    })
  }
  function formatCraftItems(items, prefix = "") {
    const resourcesReturned_items = items.reduce((acc, cur) => {
      const new_resourcesReturned_items = Object.keys(cur).filter(key => key.startsWith("resourcesReturned_")).map(k => ({[k]: cur[k]}))
      return [...acc, ...new_resourcesReturned_items]
    }, [])

    const itemRegents = {}
    items.forEach(item => {
      Object.keys(ItemIDSet[item.itemID]?.regents || {}).forEach(k => {
        if (!itemRegents[k]) {
          itemRegents[k] = (ItemIDSet[item.itemID]?.regents || {})[k]
        } else {
          itemRegents[k] += (ItemIDSet[item.itemID]?.regents || {})[k]
        }
      })
    })
    
    return {
      [`${prefix}_counts`]: items.length,
      [`${prefix}_total_result`]: items.reduce((acc, cur) => acc + (+cur.quantity), 0),
      [`${prefix}_qs_count`]: items.filter(item => item.hasIngenuityProc === "1").length,
      [`${prefix}_cn_count`]: items.filter(item => item.multicraf === "1").length,
      [`${prefix}_cy`]: resourcesReturned_items,
      [`${prefix}_regents`]: itemRegents
    }
  }
  const dateDataSource = useMemo(() => {
    const filterItems = data.dataSource.filter(item => item.date === selectDate)
    const roles = [...new Set(filterItems.map(item => item.role))]
    // console.error("roles", roles)
    const list = roles.map(role => {
      const checkRegentData = filterItems.filter(item => item.role === role && item.type === "CHECK_REAGENTS").pop()
      
      // console.error("checkRegentData0", filterItems.filter(item => item.role === role && item.type === "CHECK_REAGENTS"))
      console.error("checkRegentData", checkRegentData)
      // console.error("checkRegentData1", filterItems.filter(item => item.role === role && item.type === "CHECK_REAGENTS").shift())
      const dz_craftItems = filterItems.filter(item => item.role === role && item.type === "TRADE_SKILL_ITEM_CRAFTED_RESULT" && ["222428"].includes(item.itemID))
      const fm_craftItems = filterItems.filter(item => item.role === role && item.type === "TRADE_SKILL_ITEM_CRAFTED_RESULT" && ["223692", "223790"].includes(item.itemID))
      // console.error("craftItems", dz_craftItems, fm_craftItems)
      const mergedZZData = (function() {
        const zz_data = filterItems.find(item => item.role === role && item.type === "CHECK_REAGENTS" && item.firstCheck !== undefined)
        return zz_data ? {
          itemID_669: `${zz_data.itemID_669}-${checkRegentData.itemID_669}`, 
          itemID_668: `${zz_data.itemID_668}-${checkRegentData.itemID_668}`, 
        } : {}
      })()
      return {
        role_name: role,
        dz_stat: "",
        ...formatCraftItems(dz_craftItems, "dz"),
        ...formatCraftItems(fm_craftItems, "fm"),
        ...checkRegentData,
        ...mergedZZData,
      }
    })
    // let stat = []
    const small_stat_list = {
      "宠物币": list.reduce((acc, cur) => acc + (+cur.itemID_163036 || 0), 0),
      dz_total_result: list.reduce((acc, cur) => acc + cur.dz_total_result, 0),
      dz_counts: list.reduce((acc, cur) => acc + cur.dz_counts, 0),
      dz_qs_count: list.reduce((acc, cur) => acc + cur.dz_qs_count, 0),
      dz_cn_count: list.reduce((acc, cur) => acc + cur.dz_cn_count, 0),
      fm_total_result: list.reduce((acc, cur) => acc + cur.fm_total_result, 0),
      fm_counts: list.reduce((acc, cur) => acc + cur.fm_counts, 0),
      fm_qs_count: list.reduce((acc, cur) => acc + cur.fm_qs_count, 0),
      fm_cn_count: list.reduce((acc, cur) => acc + cur.fm_cn_count, 0),
    }
    const stat = {
      small_stat: Object.keys(small_stat_list).map(k => `[${k}=${small_stat_list[k]}]`).join(","),
      cy: formatCyList(list.reduce((acc, cur) => [...acc, ...cur.dz_cy, ...cur.fm_cy], [])),
      all_regents: (function() {
        let obj = {}
        let ls = list.reduce((acc,cur) => {
          return [...acc, cur.dz_regents, cur.fm_regents]
        }, [])
        ls.forEach(item => {
          Object.keys(item).forEach(k => {
            if (!obj[k]) {
              obj[k] = item[k]
            } else {
              obj[k] += item[k]
            }
          })
        })
        return Object.keys(obj).map(k => {
          return `${ItemIDSet[k].name}=${obj[k]}`
        })
      })(),
      // regents: filterItems.filter(e => e.type === "TRADE_SKILL_ITEM_CRAFTED_RESULT")
    }
    stat.use_regents = (function() {
      const cy_format = {}
      stat.cy.forEach(e => {
        const [k, v] = e.split("=")
        cy_format[k] = v
      })
      return stat.all_regents.map(e => {
        const [k, v] = e.split("=")
        return `${k}=${+v - +(cy_format[k] || 0)}` 
      })
    })()
    stat.craft_quality = (function() {
      let obj = {}
      filterItems.filter(item => item.type === "TRADE_SKILL_ITEM_CRAFTED_RESULT").forEach(e => {
        if (!obj[e.itemID]) {
          obj[e.itemID] = {
            count: +e.quantity || 0,
            roles: [e.role]
          }
        } else {
          obj[e.itemID].count += +e.quantity || 0
          if (!obj[e.itemID].roles.includes(e.role)) {
            obj[e.itemID].roles.push(e.role)
          }
        }
      })
      return Object.keys(obj).map(k => {
        if (!ItemIDSet[k]) return undefined
        return `${ItemIDSet[k].name}=${obj[k].count}[平均=${obj[k].count / obj[k].roles.length}]`
      }).filter(e => e)
    })()
    // console.error("stat", stat)
    return {
      tableDataSource: list,
      stat_list: stat,
      stat: Object.keys(stat).map(k => `${k}=${stat[k]}`).join(" "),
    }
  }, [data, selectDate])
  // console.error("dateDataSource", dateDataSource)
  function onConfirmClearLogFile() {
    const loadingKey = $helper.uuid()
    message.loading({ content: '正在清除...', duration: 0, key: loadingKey })
  }
  return (
    <>
    <div className='page-wrap role-page-wrap'>
      <div className="scroll-ele-wrapper">
      <Card bordered={false}>
        <Space>
          <Select className='w-64' value={selectDate} onChange={onDateChange}>
            {data.dateList.map(e => <Select.Option key={e} value={e}>{e}</Select.Option>)}
          </Select>
          <Popconfirm
            title="确定清除日志吗"
            description="清除后不可恢复，请谨慎操作！"
            okText="清除"
            cancelText="取消"
            onConfirm={onConfirmClearLogFile}
          >
            <Button type="primary" danger>清除日志</Button>
          </Popconfirm>
          
        </Space>
      </Card>
      <Card bordered={false}>
        {Object.keys(dateDataSource.stat_list || {}).map((e, idx) => <Alert className='mb-2' message={`${e}: ${dateDataSource.stat_list[e]}`} key={idx} type='success'></Alert>)}
        {/* <Alert message={dateDataSource.stat} type='success'></Alert> */}
      </Card>
      
      <Card bordered={false}>
        <Table
          scroll={{ x: 'max-content' }}
          rowKey={"role_name"}
          pagination={false}
          // className={styles.customTable}
          columns={columns}
          dataSource={dateDataSource.tableDataSource}
          bordered
          size="middle"
        />
        </Card>
        
      </div>
    </div>
      
    </>
  )
}